package com.zyc.datasettagger.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.zyc.common.entity.DataSetEntity;
import com.zyc.common.enums.ReturnCode;
import com.zyc.common.enums.RoleEnum;
import com.zyc.common.exception.BizException;
import com.zyc.datasettagger.config.security.mapper.UserMapper;
import com.zyc.datasettagger.mapper.DataSetMapper;
import com.zyc.datasettagger.mapper.SampleMapper;
import com.zyc.datasettagger.mapper.TagMapper;
import com.zyc.datasettagger.service.AuthService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

/**
 * @author zyc
 * @version 1.0
 */
@Service
@Slf4j
public class AuthServiceImpl implements AuthService {
    DataSetMapper dataSetMapper;
    SampleMapper sampleMapper;
    TagMapper tagMapper;
    UserMapper userMapper;

    @Autowired
    public AuthServiceImpl(DataSetMapper dataSetMapper, SampleMapper sampleMapper, TagMapper tagMapper, UserMapper userMapper) {
        this.dataSetMapper = dataSetMapper;
        this.sampleMapper = sampleMapper;
        this.tagMapper = tagMapper;
        this.userMapper = userMapper;
    }

    @Override
    public boolean hasDatasetOwnerRole(String datasetId) {
        DataSetEntity dataSetEntity = dataSetMapper.selectByDatasetId(datasetId);
        if (dataSetEntity == null) {
            log.warn("[hasDatasetOwnerRole]-找到不到datasetId = {} 对应的数据集", datasetId);
            throw new BizException("找不到对应的数据集", ReturnCode.DATA_NOT_FOUND);
        }
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        return dataSetEntity.getPublisherId() == userMapper.getIdByUsername(username);
    }

    @Override
    public boolean hasDatasetTaggerOrOwnerRole(String datasetId) {
        String name = SecurityContextHolder.getContext().getAuthentication().getName();
        String role = sampleMapper.getDatasetTagger(datasetId, name);
        return RoleEnum.TAGGER.getName().equals(role) ||
            RoleEnum.PUBLISHER.getName().equals(role);
    }

    @Override
    public boolean hasSampleOwnerRole(String sampleId) {
        String owner = sampleMapper.getSampleOwner(sampleId);
        return StringUtils.equals(owner, SecurityContextHolder.getContext().getAuthentication().getName());
    }
}
